import React from 'react'
import style from './style.header'
import { ImgTxt, SelectList, Link/*, Menu*/, IconFont, } from '../../ui-components'
import { Link as NewLink ,IconButton, Select } from 'sq-ui';
import MessageBlock from './MessageBlock'
import { u } from '../../actions/util'
import util from '../../util'
import store from 'yields-store'
import cookie from 'component-cookie'
import cx from 'classnames'
import { Menu } from 'sq-ui';
import { HR_NAV_LIST, HR_MANAGE_LIST, HR_REORG_LIST, HR_TEAM_LIST, HR_SETTING_LIST } from '../hr'
import { hashHistory } from 'react-router';

const HrMenu = props => (
    <ul
        className={props.className}
    >
        {
            props.list.map(item => (
                <li key={item.label}>
                    <Link label={item.label} to={item.to} className={('#'+props.path) == item.to ? style.active : ''}/>
                </li>
            ))
        }
    </ul>
)

class Header extends React.Component {

    init = {
        surveyHover: false,
        reviewHover: false,
        converHover: false,
        personalList: false,
        showSearchList: false,
        showNotifList: false,
        objectiveHover: false,
        search: '',
        searchCondition: 0, // 搜索条件
        subNav: [],
        width: 1100,
    }

    headImageCrop= (id) =>{
        let headPortrait = document.getElementById(id);
        if(headPortrait) {
            let image = document.getElementById(id).style.backgroundImage;
            let site = image.indexOf('|');
            if (site) {
                let imageUrl = image.substring(site + 1, image.length);
                let xye = imageUrl.split(',');
                if (xye.length > 2) {
                    let eSite =imageUrl.search(/[a-z|A-Z]/i);
                    xye[2] = xye[2].substring(0,eSite-1);
                    headPortrait.style.backgroundSize = `${45 / (xye[2] / 100)}px auto`;
                    headPortrait.style.backgroundPosition = `${xye[0]}% ${xye[1]}%`;
                    headPortrait.style.backgroundRepeat = 'no-repeat';
                }
            }
        }
    }

    constructor(props) {
        super(props)
        this.state = {
            ...this.init,
            hrNav: this.isHrNav(props),
            toggleSearch: false,
        }
    }

    isHrNav(props) {
        return (props || this.props).location.pathname.indexOf('/hr') === 0
    }

    handleLogout() {
        this.props.logout(() => {
            // clear token
            //store('accessToken', null)
            //store('refreshToken', null)
            cookie('X-Access-Token', null)
            cookie('X-Refresh-Token', null)
            location.href = '/u'
        })
    }

    showPersonalList() {
        this.setState({
            personalList: true
        })
        document.addEventListener('click', this.closePersonalList, false)
    }

    closePersonalList = () => {
        this.setState({
            personalList: false
        })
        document.removeEventListener('click', this.closePersonalList, false)
    }

    handleChange(e) {
        const { showSearchList, searchCondition } = this.state;
        if (!showSearchList) {
            this.setState({
                showSearchList: true
            })
        }

        const { value='' } = e.target
        if (value.trim().length) {
            util.throttle(() => {
                if(+searchCondition === 0){ // 搜索同事
                    this.props.fetchAtList(value);
                }else{ // 搜索目标/结果
                    this.props.fetchSearchList(value);
                }
            }, 300)
        } else {
            this.props.clearAtList()
        }
        this.setState({
            search: value
        })
    }

    resetSearch() {
        setTimeout(() => {
            this.setState({
                showSearchList: false,
                search: ''
            })

            this.props.clearAtList()
        }, 150)
    }

    // 更改搜索条件
    changeSearch = v => {
        this.setState({
            searchCondition: v
        })
    }

    handleBlur() {
        this.resetSearch()
        this.toggleSearch(false)
    }

    // 点击选中下拉搜索结果
    handleSearch(i) {
        const selected = this.props.atList[this.state.search][i];
        const { searchCondition, showSearchList } = this.state;
        let url = "";
        this.setState({
            search: selected.fullName,
            showSearchList: !showSearchList
        });
        // 此处需要做判断，判断搜索的是同事，还是目标/结果
        if(+searchCondition === 0){ // 跳转此人的okr页面
            url = `/okr/objective-targetAll?userId=${selected.userId}`;
        }else{ // 跳转目标/结果页面
            url = `/okr/objectives/${selected.objectiveId}`;
        }
        this.props.router.push(url);
        this.resetSearch();
    }

    getHrIndexTeamId() {
        const{ teamVO } = this.props.org
        return (teamVO || {}).teamId || null
    }

    getSubNavs() {
        let navs = []
        if (this.active('/hr')) {
            const teamId = this.getHrIndexTeamId()
            navs = [{
                label: HR_NAV_LIST[0].label,
                to: teamId? `#/hr/index?teamId=${teamId}`: null
            }]
            for (var i=1;i<HR_NAV_LIST.length;i++) {
                if (this.active('/hr/team-memeber-edit/')) {
                    navs = [
                        ...navs,
                        { label: '员工管理' }
                    ]
                    break;
                }
                const base = HR_NAV_LIST[i].to.split('/board')[0].slice(1);
                if (this.active(base + '/')) {
                    navs = [
                        ...navs,
                        { ...HR_NAV_LIST[i], ...(this.active(HR_NAV_LIST[i].to.slice(1))? {to: null}: {}) }
                    ]
                    for (var j=0; j<HR_NAV_LIST[i].menu.length; j++) {
                        if (this.active(HR_NAV_LIST[i].menu[j].to.split('?')[0].slice(1))) {
                            if (this.props.location.query.hasApproved != null) {
                                navs = [
                                    ...navs,
                                    { label: this.props.location.query.hasApproved == 0? HR_MANAGE_LIST[1].label: HR_MANAGE_LIST[2].label}
                                ]
                            } else {
                                navs = [
                                    ...navs,
                                    { label: HR_NAV_LIST[i].menu[j].label },
                                ]
                            }
                            break;
                        }

                        if (j == HR_NAV_LIST[i].menu.length-1) {
                            if (this.active('/hr/settings/profile-upload')) {
                                navs = [
                                    ...navs,
                                    { label: '邀请员工', to: '#/hr/settings/onboarding-inviting?isActivated=-1' },
                                    { label: '新增员工邀请' }
                                ]
                            }
                        }
                    }
                    return (navs.length === 1 || navs.length == 0)? []: navs
                }
            }
        }
        return (navs.length === 1 || navs.length == 0)? []: navs
    }

    renderNotifications() {
        const { liveNotifications=[] } = this.props

        return liveNotifications ? (
            <div className={style.live_notify}>
                {
                    liveNotifications.map((v, i)=>{
                        return <MessageBlock key={i} msg={v} />
                    })
                }
                <Link className={style.live_more} to="#/notifications" label="查看全部"/>
            </div>
        ) : null
    }

    showNotifList() {
        this.setState({
            showNotifList: !this.state.showNotifList
        }, () => {
            if (this.state.showNotifList) {
                this.props.fetchLiveNotificationList( ()=>
                    this.props.fetchUnreadNumber()
                )
            }
        })
        document.addEventListener('click', this.closeNotifList, false)
    }

    closeNotifList = (e) => {
        if (e.target.dataset.type != 'message') {
            this.setState({
                showNotifList: false
            })
            document.removeEventListener('click', this.closeNotifList, false)
        }
    }

    componentDidMount() {
        this.props.fetchOrg()
        util.bus.on('page:resize', this.resize);
        this.resize();
    }

    componentWillReceiveProps(props) {
        if(this.props.org.avatarUrl && props.org.avatarUrl) {
            this.headImageCrop("logo");
        }
    }

    resize = () => {
        const clientWidth = document.documentElement.clientWidth;
        if (clientWidth < 1024) return;
        if ( clientWidth > 1280) {
            this.setState({
                width: 1100
            });
        } else {
            this.setState({
                width: 1100 - (1280 - clientWidth),
            })
        }
    }

    getSurveyChartUrl() {
        let url = "/charts#/e/survey";
        if (this.props.location.pathname === '/e/survey') {
            return url + '?' + util.body(this.props.location.query);
        }
        return url + '?tab=1';
    }

    active(path) {
        return this.props.location.pathname.indexOf(path) == 0
    }
    toggleSearch = (flag) => {
        if(flag){
            this.refs.searchInput.focus();
        }
        this.setState({
            toggleSearch: flag,
            search: "",
            showSearchList: false,
        });
    }
    renderUserNav() {
        const { org, myProfile, unread, profile } = this.props
        const { roleNameList, teamVO } = profile
        if (!roleNameList) return null
        if (this.isHrNav()) return this.loginNav();
        return (
            <ul className={style['user-nav']}>
                <li style={{position: 'relative'}}>
                    <div className={cx({
                        [style.search]: true,
                        [style['search-active']]: this.state.toggleSearch,
                    })}>
                        <IconButton
                            icon="search"
                            onClick={this.toggleSearch.bind(this, true)}
                        />
                        <Select
                            className={style['search-condition']}
                            value={this.state.searchCondition}
                            onChange={v => this.changeSearch(v)}
                            style={{width: '96px'}}
                            list={[
                                '同事',
                                '目标/结果',
                            ]}
                            item={(v, i) => (
                                <li data-value={i} key={i}>
                                    <span>{v}</span>
                                </li>
                            )}
                        />
                        <div className={style['search-input']}>
                            <input
                                ref={'searchInput'}
                                value={this.state.search}
                                onChange={::this.handleChange}
                                // onBlur={::this.handleBlur}
                                // placeholder="查找更多同事"
                            />
                            <SelectList
                                className={style['search-list']}
                                data={this.props.atList[this.state.search]} // 匹配搜索的关键字在返回的结果对象中的数据
                                handleSelect={::this.handleSearch} // 下拉选择的回调
                                show={this.state.showSearchList} // 是否展示列表数据
                            />
                        </div>
                        <div className={style['search-close']}>
                            <IconButton
                                icon="close"
                                onClick={this.toggleSearch.bind(this, false)}
                            />
                        </div>
                    </div>
                </li>
                <li style={{ marginLeft: '4px' }} className={cx(style.unread, {
                    [style.active]: this.active('/notifications') || this.state.showNotifList
                })}>
                    <Link
                        to={(unread != null && unread == 0)? '#/notifications': null}
                        className={style['header-icon']}
                        onClick={e => {
                            if (this.state.showNotifList) {
                                e.preventDefault()
                            }
                            if(unread > 0) {
                                this.showNotifList()
                            }
                        }}
                        icon="message"
                    />
                    {
                        this.props.unread ? <i title={this.props.unread}></i> : null
                    }
                    {
                        this.state.showNotifList ? this.renderNotifications() : null
                    }
                </li>
                {
                    ~roleNameList.indexOf('superAdmin')?
                        <li style={{ marginLeft: '4px' }} className={cx({
                            [style.active]: this.active('/system')
                        })}>
                            <Link icon="settings" className={style['header-icon']} to='/admin'/>
                        </li>: null
                }
                {
                    this.loginNav()
                }
            </ul>
        );
    }

    // 不是founder的时候才会展示团队
    notFounder() {
        const { org, profile } = this.props
        if (util.isNull(org) || util.isNull(org.teamVO) || util.isNull(profile) || util.isNull(profile.teamVO)) return false;

        return !util.isEqual(org.teamVO.teamId, profile.teamVO.teamId);
    }

    renderAppNav() {
        const { org, myProfile, unread, profile } = this.props
        const { roleNameList, teamVO, hasReportee } = profile
        if (!roleNameList) return null

        const isHr = ~roleNameList.indexOf('HR');
        const isOrgAdmin = ~roleNameList.indexOf('orgAdmin');

        // 目标链接
        let personalLink = `/okr?type=3&userId=${profile.userId}&teamId=${profile.teamVO.teamId}`;
        let teamLink = `/okr?type=2&teamId=${profile.teamVO.teamId}`;
        let orgLink = `/okr?type=1&teamId=${(org.teamVO || {}).teamId}`;

        const { pathname, query } = this.props.location;
        let isPersonal;
        let isTeam;
        let isOrg;
        if (pathname.indexOf('/okr') === 0 && !~pathname.indexOf('/okr/objectives/')) {
            const { teamId, type, userId } = query;
            isPersonal = type == 3 && userId == profile.userId;
            isTeam = type == 2 && teamId == profile.teamVO.teamId;
            isOrg = type == 1;
            // 个人
            if (isPersonal) {
                personalLink = `${pathname}?${util.body(query)}`;
            }
            // 团队
            else if(isTeam) {
                teamLink = `${pathname}?${util.body(query)}`;
            }
            // 公司
            else if(isOrg) {
                orgLink = `${pathname}?${util.body(query)}`;
            }
        }

        return (
            <div className={style['app-nav-wrapper']}>
                <ul className={style.list}>
                    <li>
                        <Link
                            className={cx({
                                [style.active]: this.active('/home')
                            })}
                            onClick={() => {
                                if (this.props.location.pathname.indexOf('/charts') === 0) {
                                    location.href = '/';
                                } else {
                                    hashHistory.push({
                                        pathname: '/',
                                    });
                                }
                            }}
                            label="首页"
                        />
                    </li>
                    {
                        (!util.isNull(profile) && !util.isNull(org)) ?
                            <li
                                className={cx(style.objective, {
                                    [style.hover]: this.state.objectiveHover,
                                })}
                                onMouseEnter={() => this.setState({ objectiveHover: true })}
                                onMouseLeave={() => this.setState({ objectiveHover: false })}
                                onClick={() => this.setState({ objectiveHover: false })}
                            >
                                <NewLink label="目标管理" to={personalLink} className={cx({
                                    [style.active]: this.active('/okr')
                                })}
                                />
                                {
                                    (util.isNull(profile) || util.isNull(org) || !this.state.objectiveHover) ? null : (
                                        <ul>
                                            <li>
                                                <NewLink
                                                    to={personalLink}
                                                    label="目标管理"
                                                />
                                            </li>
                                            <li
                                                className={isOrg? style.active: ''}
                                            >
                                                <NewLink
                                                    to={orgLink}
                                                    label="公司目标"
                                                />
                                            </li>
                                            {
                                                this.notFounder() ?
                                                    <li
                                                        className={isTeam? style.active: ''}
                                                    >
                                                        <NewLink
                                                            to={teamLink}
                                                            label="团队目标"
                                                        />
                                                    </li> :
                                                    <li
                                                        className={isTeam? style.active: ''}
                                                    >
                                                        <NewLink
                                                            to={orgLink}
                                                            label="团队目标"
                                                        />
                                                    </li>
                                            }

                                            {/* <li
                    className={isTeam? style.active: ''}
                  >
                    <NewLink
                      to={isTeam?teamLink:orgLink}
                      label="团队目标"
                    />
                  </li> */}

                                            <li
                                                className={isPersonal? style.active: ''}
                                            >
                                                <NewLink
                                                    to={personalLink}
                                                    label="个人目标"
                                                />
                                            </li>
                                            <li>
                                                <NewLink
                                                    to='/okr/objective-all'
                                                    label="全部目标"
                                                />
                                            </li>
                                        </ul>
                                    )
                                }
                            </li>: null
                    }
                    <li
                        className={cx(style.objective, {
                            [style.hover]: this.state.converHover,
                        })}
                        onMouseEnter={() => this.setState({ converHover: true })}
                        onMouseLeave={() => this.setState({ converHover: false })}
                        onClick={() => this.setState({converHover: false })}
                    >
                        <NewLink label="当面交谈" to="/conversation/initiate" className={cx({
                            [style.active]: this.active('/conversation')
                        })}/>
                        {
                            (this.state.converHover) ? (
                                <ul>
                                    <li>
                                        <NewLink
                                            to="/conversation/initiate"
                                            label="当面交谈"
                                        />
                                    </li>
                                    <li>
                                        <NewLink
                                            to="/conversation/initiate"
                                            label="发起交谈"
                                        />
                                    </li>
                                    <li>
                                        <NewLink
                                            to="/conversation/record"
                                            label="受邀交谈记录"
                                        />
                                    </li>
                                    <li>
                                        <NewLink
                                            label="交谈看板" onClick={e=>{
                                            if(location.href.indexOf('charts/#/e/converchart') === -1){
                                                location.href='charts#/e/converchart'
                                            }
                                            // location.href='charts#/e/converchart'
                                        }}/>
                                    </li>
                                </ul>
                            ) : null
                        }
                    </li>
                    <li
                        className={cx(style.objective, {
                            [style.hover]: this.state.reviewHover,
                        })}
                        onMouseEnter={() => this.setState({ reviewHover: true })}
                        onMouseLeave={() => this.setState({ reviewHover: false })}
                        onClick={() => this.setState({reviewHover: false })}
                    >
                        <NewLink label="反馈活动" to="/review/index/default" className={cx({
                            [style.active]: this.active('/review')
                        })}/>
                        {
                            (isHr && this.state.reviewHover) ? (
                                <ul>
                                    <li>
                                        <NewLink
                                            to="/review/index/default"
                                            label="反馈活动"
                                        />
                                    </li>
                                    <li>
                                        <NewLink
                                            to="/review/index/default"
                                            label="查看反馈活动"
                                        />
                                    </li>
                                    <li>
                                        <NewLink label="反馈活动管理" to="/review/admin"/>
                                    </li>
                                </ul>
                            ) : null
                        }
                    </li>
                    <li
            className={cx(style.objective, {
              [style.hover]: this.state.surveyHover,
            })}
            onMouseEnter={() => this.setState({ surveyHover: true })}
            onMouseLeave={() => this.setState({ surveyHover: false })}
            onClick={() => this.setState({surveyHover: false })}
          >
            <NewLink label="匿名调研" to="/survey/activity" className={cx({
              [style.active]: this.active('/survey')
            })}/>
            {
              ((isHr || isOrgAdmin) && this.state.surveyHover) ? (
                <ul>
                  <li>
                    <NewLink
                      to="/survey/activity"
                      label="匿名调研"
                    />
                  </li>
                  <li>
                    <NewLink
                      to="/survey/activity"
                      label="填写问卷"
                    />
                  </li>
                  {
                    isHr ?
                    <li>
                      <NewLink label="调研管理" to="/survey"/>
                    </li>
                    : null
                  }
                  <li>
                    <Link label="调研看板" to={this.getSurveyChartUrl()} style={{color: '#fff'}}/>
                  </li>
                </ul>
              ) : null
            }
          </li>
                    <li>
                        <Link className={cx({
                            [style.active]: this.active('/newsfeed')
                        })} to="#/newsfeed" label="赞赏墙"/>
                    </li>
                    <li>
                        <Link className={cx({
                            [style.active]: this.active('/team')
                        })}  to={(teamVO || {}).teamId? `#/team/myTeam?teamId=${teamVO.teamId}`: null} label="团队"/>
                    </li>
                </ul>

            </div>
        )
    }

    loginNav() {
        const { myProfile } = this.props;;
        return (
            <li
                className={style.settings}
                onMouseEnter={::this.showPersonalList}
                onMouseLeave={::this.closePersonalList}
                style={{ cursor: 'pointer'}}
            >

                <Link
                    className={style['settings-avatar']}
                    srcIcon="avatar"
                    width="30"
                    src={this.props.profile.avatarUrl}
                />
                <IconFont value='arrow' className={style.arrow}/>
                {
                    this.state.personalList?
                        <ul>
                            <li>
                                <Link
                                    label="我的主页"
                                    // 个人主页不做跳转
                                    to={`#/user/${u.userId}`}/>
                            </li>
                            <li>
                                <Link
                                    label="个人设置"
                                    to="#/personal/basic?from=head"/>
                            </li>
                            {
                                myProfile.onboardingTemplateId?
                                    <li>
                                        <Link
                                            label="公司文档"
                                            to={`#/company-documents?onboardingTemplateId=${myProfile.onboardingTemplateId}`} />
                                    </li>: null
                            }
                            <li>
                                <Link
                                    onClick={::this.handleLogout}
                                    label="退出"
                                />
                            </li>
                        </ul>: null
                }
            </li>
        )
    }

    renderHrNav() {
        const { profile } = this.props
        const basePath = /(\/\w+\/\w+)\/?/
        const isActive = clicked => {
            const { pathname } = this.props.location
            const urlBasePath = basePath.exec(pathname)
            const curBasePath = basePath.exec(clicked)
            if (!urlBasePath || !curBasePath) return
            return urlBasePath[1] === curBasePath[1]
        }
        return (
            <div>
                <ul className={style['hr-nav-list']}>
                    {
                        HR_NAV_LIST.map((item, i) => (
                            <li
                                key={item.label}
                                className={cx({
                                    [style.active]: isActive(HR_NAV_LIST[i].to)
                                })}
                            >
                                {
                                    i === 0? (
                                        <Link label={item.label} to={item.to(this.getHrIndexTeamId())}/>
                                    ): (
                                        <Menu showByHover center className={style['hr-nav-menu']}>
                                            <Link label={item.label} to={item.to} />
                                            <HrMenu list={item.menu} path={this.props.location.pathname + (util.isNull(this.props.location.query) ? '' : ('?' + util.body(this.props.location.query)))}/>
                                        </Menu>
                                    )
                                }
                            </li>
                        ))
                    }

                </ul>
            </div>
        );
    }

    renderNav() {
        if (!this.isHrNav()) return this.renderAppNav()
        return this.renderHrNav()
    }

    renderSubNav() {
        const subNav = this.getSubNavs() || []
        if (!subNav.length) return null
        return (
            <div style={{width: '100%'}} className={style['header-sub-navs']}>
                <ul>
                    {
                        subNav.map(item => (
                            <li key={item.label}>
                                {
                                    item.to?
                                        <span className={style['nav-link']}>
                    <Link label={item.label} to={item.to} />
                    <IconFont value="arrow" rotate="-90"/>
                  </span>
                                        : <span>{item.label}</span>
                                }
                            </li>
                        ))
                    }
                </ul>
            </div>
        );
    }

    render() {
        const { unread, org, profile, myProfile } = this.props
        const { teamVO } = org
        const { roleNameList=[] } = profile
        const { avatarUrl='' } = profile
        const hrNav = this.isHrNav()
        return (
            <div className={cx(style.root, {
                [style['hr-nav']]: hrNav
            })}>
                <div style={{ width: `${this.state.width}px` }}>
                    <div>
                        <Link
                            to='#/'
                            className={style.logo}
                            id="logo"
                            width = "45px"
                            src={org.avatarUrl || `/${util.getImagePath()}/default/wozai.png`}
                        />

                        {
                            this.renderNav()
                        }

                    </div>

                    { this.renderUserNav() }
                </div>

                {
                    ~roleNameList.indexOf('HR')?
                        <Link
                            to={hrNav? '#/home': `#/hr/index?teamId=${this.getHrIndexTeamId()}`}
                            label={hrNav? "返回": "人事管理"}
                            className={cx(style.hr,{
                                [style.active]: hrNav
                            })}
                        />: null
                }
                {
                    this.renderSubNav()
                }
            </div>
        )
    }
}

export default Header
